<template>
  <div class="app-container">
    <div>
      <p class="dialogTitle title">当前地震事件: 
        <span v-if="currentEvent">{{ currentEvent.eventName }}</span>
        <span v-else>请在地震事件管理中设置当前地震事件</span>
      </p>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px" v-show="showSearch">
      <el-form-item label="知识库类型" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择知识库类型" clearable>
          <el-option v-for="item in option" :key="item.dictItemCode" :label="item.dictItemName" :value="item.dictItemCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="知识库名称" prop="knowledgeName">
          <el-input v-model="queryParams.knowledgeName" placeholder="请输入知识库名称"  clearable />
      </el-form-item>
      <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" :disabled="!currentEvent" @click="handleAdd">新建</el-button>
        </el-col>
        <el-col :span="1.5">
                <el-button plain icon="Download" :disabled="!currentEvent" @click="handleImport">导入</el-button>
        </el-col>
        <el-col :span="1.5">
                <el-button plain icon="Edit" :disabled="!currentEvent||dataList.length==0" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" stripe>
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope">
            <span>{{(queryParams.page - 1) * queryParams.rows + scope.$index + 1}}</span>
          </template>             
        </el-table-column>
        <el-table-column label="类型" align="center" prop="category">
          <template #default="scope">
              <span>{{getCategory(scope.row.category)}}</span>
          </template>   
        </el-table-column>
        <el-table-column label="知识库编号" align="center" prop="knowledgeCode" show-overflow-tooltip>
          <template #default="scope">
            <span style="color: #107ce1;cursor: pointer;" @click="handleEdit(scope.row)">{{ scope.row.knowledgeCode }}</span>
          </template>   
        </el-table-column>
        <el-table-column label="知识库名称" align="center" prop="knowledgeName" />
        <el-table-column label="创建单位" align="center" prop="company" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">         
			      <el-button type="text" @click="handleDownload(scope.row)" v-if="scope.row.attachment">附件下载</el-button>
			      <el-button type="text" @click="handleEdit(scope.row)" v-else>上传附件</el-button>
			      <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"   @pagination="getList" /> 
      
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="addRef" label-width="120px" :model="form" :rules="rules">
        <el-row style="margin: 20px 0;">    
            <el-col>
              <el-form-item label="知识库类型" prop="category" clearable>
                <el-select v-model="form.category" placeholder="请选择知识库类型" clearable @change="getKnowledCode" style="width:100%">
                  <el-option v-for="item in option" :key="item.dictItemCode" :label="item.dictItemName" :value="item.dictItemCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="知识库编号" prop="knowledgeCode" required>
                <el-input v-model="form.knowledgeCode" placeholder="请输入知识库编号"  disabled />
              </el-form-item>
            </el-col>            
            <el-col>
              <el-form-item label="知识库名称" prop="knowledgeName">
                <el-input v-model="form.knowledgeName" placeholder="请输入知识库名称"  clearable />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="附件" prop="attachment">
                <file-upload ref="fileUploadRef" :limit="1" v-model="form.attachments" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="描述信息" prop="commentInfo">
                <el-input v-model="form.commentInfo" type="textarea" maxlength="500" show-word-limit :autosize="{ minRows: 5, maxRows: 5 }" placeholder="请输入描述信息" clearable/>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="创建人单位" prop="company" required>
                <el-input v-model="form.company" placeholder="请输入创建单位"  disabled />
              </el-form-item>
            </el-col>   
            <el-col>
              <el-form-item label="创建人" prop="createUser" required>
                <el-input v-model="form.createUser" placeholder="请输入创建人"  disabled />
              </el-form-item>
            </el-col>            
            <el-col>
              <el-form-item label="创建时间" prop="createTime" required>
                <el-input v-model="form.createTime" placeholder="请输入创建时间"  disabled />
              </el-form-item>
            </el-col>

        </el-row>         
      </el-form>
      <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="save">保 存</el-button>
              <el-button @click="open = false">取 消</el-button>
          </div>
      </template>
    </el-dialog>          
    
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
          <p></p>
           <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload" :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess" :data="{'xsemId':currentEvent.id}" :auto-upload="false" drag>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                 <div class="el-upload__tip text-center">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('知识库导入模板.xlsx')">下载模板</el-link>
                 </div>
              </template>
           </el-upload>
           <template #footer>
              <div class="dialog-footer">
                 <el-button type="primary" @click="submitFileForm">确 定</el-button>
                 <el-button @click="upload.open = false">取 消</el-button>
              </div>
           </template>
        </el-dialog>
  </div>
</template>

<script setup name="knowledge">
import useEventStore from "@/store/modules/event";
import { getAllList, getCode, saveData, getDetail, updateData ,getCreateInfo, del, getKnowledgeCode } from "@/api/comprehensiveInformation/knowledge.js"
import { getToken } from "@/utils/auth";
import { getDict } from "@/api/system/dict";
const currentEvent = computed(() => useEventStore().currentEvent);
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showSearch = ref(true);
const open = ref(false);
const title = ref();
const option = ref([]);
/*** 导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "token " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/knowledgeManagement/importExcel"
});
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        category: undefined,
        knowledgeName: undefined,
    },
    form: {
    },
    rules: {
      knowledgeCode: [{required: true, message: "知识库编号不能为空", trigger: "change" }],
      knowledgeName:[{ required: true, message: "知识库名称不能为空", trigger: "blur" }],
      category:[{ required: true, message: "知识库类型不能为空", trigger: "change" }],
      attachment:[{ required: true, message: "附件不能为空", trigger: "change" }],
    }
})
const { queryParams, form, rules } = toRefs(data)

// 下载文件
function handleDownload(row) {
  var query = {
    attachId: row.attachment,
    name: row.name
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

// 新增
function handleAdd(){
  title.value = '新建知识库信息';
  getInfo();
}
function getInfo(){
  getKnowledgeCode({xsemId:currentEvent.value.id}).then(res=>{
    open.value = true;
    proxy.resetForm("addRef");
    form.value = res.data;
    form.value.attachments = [];
  })
}
// 编辑
function handleEdit(row){
  title.value = '编辑知识库信息'
  detail(row.xkmId);
}
// 查看
function detail(id){
  getDetail({id:id}).then(res=>{
    open.value = true;
    proxy.resetForm("addRef");
    form.value = res.data;
    form.value.attachments=res.data.attachmentInfoEntity?[res.data.attachmentInfoEntity]:[];
  })
}
function getKnowledCode(value) {
  if(value == '1') {
    getCode({eventCode: ''}).then(res => {
      form.value.knowledgeCode = res.data
    }).catch()
  }else{
    getCode({eventCode: currentEvent.value.eventCode}).then(res => {
      form.value.knowledgeCode = res.data
    }).catch()
  }
  
}
// 保存
function save(){
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["fileUploadRef"].fileList));
  const attachIds = [];
  for (var i = 0; i < fileList.length; i++) {
    attachIds.push(fileList[i].attachId)
  }
  form.value.attachment = attachIds.join(",");
  proxy.$refs["addRef"].validate(valid => {
    if (valid) {

      if(title.value=='新建知识库信息'){
        saveData({...form.value,xsemId:form.value.category=='2'?currentEvent.value.id:''}).then(res=>{
          proxy.$modal.msgSuccess("新建成功");
          open.value = false;
          getList();
        })
      }else{
        updateData({...form.value,xsemId:form.value.category=='2'?currentEvent.value.id:''}).then(res=>{
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getList();
        })
      }
    }
  })

}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
			.confirm("是否确认删除该信息，请确认是否要删除？", )
			.then(function() {
				return del(row.xkmId);
			})
			.then(() => {
				getList();
				proxy.$modal.msgSuccess("删除成功");
			})
			.catch(() => {});
}

// 模板下载
function importTemplate(name) {
  proxy.downloadTemplate("/template/download", {
    fileName:name
  }, name);
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 导出按钮操作 */
function handleExport() {
  proxy.downloadTemplate('/knowledgeManagement/exportData', {xsemId:currentEvent.value.id,...queryParams.value}, `知识库管理.xls`)
}

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
  proxy.$modal.closeLoading();                                                                          
  proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  let { code, message } = response;
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
  proxy.$refs["uploadRef"].handleRemove(file);
  if(code==200){
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "<font size='5px' color='green'>导入成功！</font>" + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  }else{
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  }
  getList();
};


/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() { 
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 查询数据列表 */
function getList() {
  if(currentEvent.value){
    loading.value = true;
    getAllList({...queryParams.value,xsemId:currentEvent.value.id}).then(response => {
        dataList.value = response.data.rows ? response.data.rows : [];
        total.value = response.data.total;
        loading.value = false;
    }).catch(err=>{loading.value = false});
  }else{
    dataList.value = [];
    total.value = 0;
  }
}

/** 获取字典值 */
async function getDictData() {
await getDict("zsk").then(response => {
	    option.value = response.data;
	});
}
function getCategory(val){
	var name = ''
	option.value.forEach(item => {
		if(item.dictItemCode == val) {
			name = item.dictItemName
			return
		}
	})
	return name
}

onMounted(() => {
  setTimeout(()=>{
    getList();
  },200)
})
getDictData();
</script>

<style scoped lang="scss">
.title{
  margin: 0 0 20px!important;
}
</style>

